package com.cn.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cn.common.utils.LoggerUtils;
import com.cn.common.utils.StringUtils;
import com.cn.shiro.entity.UUser;

@Controller
public class LoginController {
	
	
	@RequestMapping(value="/login",method= RequestMethod.GET)
    public String login(){
        return "index/index";
    }

	/**
	 * 后期改为异步调用，展示错误信息
	 * @param request
	 * @param user
	 * @param model
	 * @return
	 */
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(UUser user, Model model){
    	LoggerUtils.debug(LoginController.class, "来了！！！");
        if (StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPswd())) {
        	LoggerUtils.debug(LoginController.class, "用户名或密码不能为空！");
        	model.addAttribute("msg", "用户名或密码不能为空！");
            return "index/index";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getEmail(),user.getPswd());
        try {
            subject.login(token);
            //用log代替system.out 
            LoggerUtils.debug(LoginController.class, "登陆啦啦啦！！！");
            return "redirect:/homepage/fapai";
        }catch (LockedAccountException lae) {
        	LoggerUtils.debug(LoginController.class, "用户已经被锁定不能登录，请与管理员联系！");
            token.clear();
            model.addAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
            return "index/index";
        } catch (AuthenticationException e) {
        	LoggerUtils.debug(LoginController.class, "用户或密码不正确！");
            token.clear();
            model.addAttribute("msg", "用户或密码不正确！");
            return "index/index";
        }
    }
}
